package me.zhengjie.modules.weixin.analyzer.impl;

import me.zhengjie.modules.weixin.analyzer.AbstractAnalyzer;
import me.zhengjie.modules.weixin.dto.WeChatAccount;
import me.zhengjie.modules.weixin.dto.WeChatMessage;
import me.zhengjie.modules.weixin.enums.WeChatEventEnum;
import me.zhengjie.modules.weixin.message.AnalyzerReplyMessage;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TextAnalyzer extends AbstractAnalyzer {

    public TextAnalyzer() {

    }

    public TextAnalyzer(WeChatAccount account, Map<String, Object> message) {
        this.account = account;
        this.message = message;
    }

    @Override
    public WeChatMessage analyze() {
        String event = WeChatEventEnum.text.name();
        String openid = (String) message.get("FromUserName");

        final String eventKey = StringUtils.defaultString((String) message.get("EventKey"));
        WeChatMessage weChatMessage = account.getMessages().parallelStream()
                .filter(m -> Arrays.asList(m.getMsgType().split("\\|")).contains(event)).findFirst().orElse(new WeChatMessage());

        weChatMessage.setMsgType(event);
        List<AnalyzerReplyMessage> replyMessages = weChatMessage.getReplyMessage().parallelStream()
                .filter(r -> r.getRule().equals("*") || r.getRule().equalsIgnoreCase(eventKey))
                .sorted(Comparator.comparing(AnalyzerReplyMessage::getPriority))
                .limit(1).collect(Collectors.toList());

        // 定位到精确的一条回复即可
        weChatMessage.setReplyMessage(replyMessages);
        return weChatMessage;
    }
}
